package org.dolphin.dao.impl;

import java.util.Date;
import java.util.List;
import org.dolphin.dao.SeasonalPromotionDao;
import org.dolphin.dao.util.SessionHelper;
import org.dolphin.entity.inventory.Product;
import org.dolphin.entity.inventory.ProductAttribute;
import org.dolphin.entity.promo.ProductAttributeSeasonalPromotion;
import org.dolphin.entity.promo.ProductSeasonalPromotion;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "seasonalPromotionDao")
public class SeasonalPromotionDaoImpl implements SeasonalPromotionDao {
  @Autowired(required = true)
  private SessionFactory sessionFactory;

  @SuppressWarnings("unchecked")
  @Override
  public ProductSeasonalPromotion getPromotion(Product product, Date priceItemDate) {
    DetachedCriteria dc = DetachedCriteria.forClass(ProductSeasonalPromotion.class);
    dc.add(Restrictions.eq("product", product));
    dc.add(Restrictions.eq("active", Boolean.TRUE));
    Conjunction conjunction = Restrictions.conjunction();
    conjunction.add(Restrictions.ge("startDate", priceItemDate));
    conjunction.add(Restrictions.le("endDate", priceItemDate));
    dc.add(conjunction);
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = dc.getExecutableCriteria(session);
    List<ProductSeasonalPromotion> list = criteria.list();
    if (list != null && !list.isEmpty()) {
      return list.get(0);
    }
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public ProductAttributeSeasonalPromotion getPromotion(ProductAttribute attribute,
      Date priceItemDate) {
    DetachedCriteria dc = DetachedCriteria.forClass(ProductAttributeSeasonalPromotion.class);
    dc.add(Restrictions.eq("productAttribute", attribute));
    dc.add(Restrictions.eq("active", Boolean.TRUE));
    Conjunction conjunction = Restrictions.conjunction();
    conjunction.add(Restrictions.ge("startDate", priceItemDate));
    conjunction.add(Restrictions.le("endDate", priceItemDate));
    dc.add(conjunction);
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = dc.getExecutableCriteria(session);
    List<ProductAttributeSeasonalPromotion> list = criteria.list();
    if (list != null && !list.isEmpty()) {
      return list.get(0);
    }
    return null;
  }
}
